﻿using UnityEngine;

public class MonoSingleton<T>
    : MonoBehaviour where T : MonoSingleton<T>
{
    private static T _instance = null;
    private static object _lock = new object();

    protected MonoSingleton()
    {

    }

    private static bool _aplicationIsQuitting = false;
    public static T Instance {
        get {
            if (_aplicationIsQuitting) {
                Debug.LogWarningFormat("[Singleton] Instance '{0}' already destroyed on application quit. Won't create again - return null.",
                    typeof(T));
            }
            lock (_lock) {
                if (null == _instance) {
                    T[] allInstances = FindObjectsOfType<T>();
                    if (1 == allInstances.Length) {
                        _instance = allInstances[0];
                        Debug.LogFormat("[Singleton '{0}' is already created: {1}.", typeof(T), _instance.gameObject.name);
                    } else if (0 == allInstances.Length) {
                        GameObject objSingleton = new GameObject(
                            string.Format("MonoSingleton<{0}>", typeof(T).ToString())
                            );
                        _instance = objSingleton.AddComponent<T>();
                        DontDestroyOnLoad(objSingleton);
                    } else {
                        Debug.LogError("[Singleton] Something went really wrong - there should never be more than one Singleton! Reopenning the scene might fix it.");
                    }
                }
            }
            return _instance;
        }
    }

    protected void OnDestroy()
    {
        _aplicationIsQuitting = true;
    }

}
